//
//  MineViewController.m
//  ATMCash
//
//  Created by zhengchengfeng on 2024/9/3.
//

#import "MineViewController.h"
#import "PersonCenterTableCell.h"

#define kTabCell    @"kTabCell"

#define kFix                30
#define kHeadImgHeight      200
#define kHeadBackImgHeight  (kScreenWidth - 20 - 40 - kFix*2)/3 *2 + 140

#define kHeadViewHeight     kNavigationBarHeight + kHeadImgHeight + kHeadBackImgHeight

@interface MineViewController ()

@property (nonatomic) PersonCenterModel *model;

@property (nonatomic) UIImageView *headBgImg;

@property (nonatomic) BOOL isOffsetY;

@end

@implementation MineViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = self.tableView.backgroundColor = RGB(4, 44, 8);
    
    [self initHeadView];
    
    [CreaditUtilsHelper boxShowLoadWithMessage:@"" onView:self.view withOffsetHeight:0];
    [self loadData];
    [self.tableView registerClass:[PersonCenterTableCell class] forCellReuseIdentifier:kTabCell];
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kGeneralHeight)];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:kNotificationMsg_Land_Sucess object:nil];
    
}
- (void)initHeadView{
    
    UIImage *imgHeadBack = [UIImage imageNamed:@"icon_pcTop1"];
    UIImage *btnBackImg = [UIImage imageNamed:@"icon_btnBgv1"];
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, DimensionBaseIphone6(imgHeadBack.size.height + btnBackImg.size.height + 15))];
    headView.backgroundColor = [UIColor clearColor];
    headView.userInteractionEnabled = YES;
    self.tableView.tableHeaderView = headView;
    
    UIImageView *imgBackV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, DimensionBaseIphone6(imgHeadBack.size.height))];
    imgBackV.image = imgHeadBack;
    [headView addSubview:imgBackV];
    self.headBgImg = imgBackV;
    
    UILabel *lab = [Utility createLabel:[UIFont fontWithName:kFuturaMedium size:16] color:[UIColor whiteColor]];
    lab.text = @"Person Center";
    lab.textAlignment = 1;
    lab.frame = CGRectMake(0, DimensionBaseIphone6(44), kScreenWidth, DimensionBaseIphone6(44));
    [headView addSubview:lab];
    
    UIImage *img2 = [UIImage imageNamed:@"icon_pcTop2"];
    UIImageView *imgV2 = [[UIImageView alloc] initWithFrame:CGRectMake(20, lab.bottom, kScreenWidth - 40, DimensionBaseIphone6(img2.size.height))];
    imgV2.image = img2;
    [headView addSubview:imgV2];
    
    CGFloat ww = DimensionBaseIphone6(100);
    UIImage *img3 = [UIImage imageNamed:@"icon_headerLogo"];
    UIImageView *headImgV = [[UIImageView alloc] initWithFrame:CGRectMake((imgBackV.width - ww)/2, kNavigationBarHeight + DimensionBaseIphone6(50), ww, ww)];
    headImgV.image = img3;
    [headView addSubview:headImgV];
    
    UILabel *phoneLab = [Utility createLabel:[UIFont fontWithName:kFutura size:22] color:[UIColor colorWithHexString:@"#FFEFC0"]];
    NSString *phoneStr = [StringUtil starsReplacedOfString:esString([[NSUserDefaults standardUserDefaults] valueForKey:kUserNameKey]) withinRange:NSMakeRange(2, 4)];
    phoneLab.text = [NSString stringWithFormat:@"%@~%@",@"Hi",esString(phoneStr)];
    phoneLab.frame = CGRectMake(0, headImgV.bottom  + DimensionBaseIphone6(8), kScreenWidth, DimensionBaseIphone6(30));
    [headView addSubview:phoneLab];
    phoneLab.textAlignment = 1;
    
    

    
//    UIImageView *backIMG = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - DimensionBaseIphone6(btnBackImg.size.width))/2, imgBackV.bottom + DimensionBaseIphone6(15), DimensionBaseIphone6(btnBackImg.size.width), DimensionBaseIphone6(btnBackImg.size.height))];
    UIImageView *backIMG = [[UIImageView alloc] initWithFrame:CGRectMake(15, imgBackV.bottom + DimensionBaseIphone6(10), kScreenWidth - 30, DimensionBaseIphone6(btnBackImg.size.height))];
    backIMG.userInteractionEnabled = YES;
    backIMG.image = btnBackImg;
    if (self.data.count  > 0) {
        [headView addSubview:backIMG];
    }
    
    
   
    CGFloat btnW = (backIMG.size.width - 40 - kFix*2)/3;
    CGFloat btnH = btnW;
    
    if (self.data.count  > 0) {
        
        for (int i=0; i<self.data.count; i++) {
            
            self.model = self.data[i];
            
            UIButton *btn = [[UIButton alloc] init];
            btn.frame = CGRectMake(20+btnW*(i%3) + kFix*(i%3), 70 + btnH*(i/3) + 40*(i/3), btnW, btnH);
            [btn setBackgroundImage:[UIImage imageNamed:@"icon_btnBgv2"] forState:UIControlStateNormal];
            [backIMG addSubview:btn];
            btn.tag = i;
            [btn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
            
//            if (PMStringIsEmpty(self.model.btnImg)) {
//                [btn sd_setImageWithURL:[NSURL URLWithString:esString(self.model.station)] forState:UIControlStateNormal];
//            } else {
//                [btn setImage:[UIImage imageNamed:esString(self.model.btnImg)] forState:UIControlStateNormal];
//            }
            
            
            UIImageView *btnImgV = [[UIImageView alloc] init];
            if (PMStringIsEmpty(self.model.btnImg)) {
                [btnImgV sd_setImageWithURL:[NSURL URLWithString:esString(self.model.station)]];
            } else {
                btnImgV.image = [UIImage imageNamed:esString(self.model.btnImg)];
            }
            [btn addSubview:btnImgV];
            btnImgV.frame = CGRectMake(21, 21, btnW - 42, btnH - 42);
            
            
            UILabel *lab = [Utility createLabel:[UIFont fontWithName:kFuturaMedium size:12] color:[UIColor whiteColor]];
            lab.text = esString(self.model.ego);
            lab.textAlignment = 1;
            
            lab.frame = CGRectMake(0, btn.bottom, btn.width + 30, DimensionBaseIphone6(40));
            lab.centerX = btn.centerX;
            [backIMG addSubview:lab];
            lab.adjustsFontSizeToFitWidth = YES;
            
            
        }
        
    }
    
    [self.tableView reloadData];
    
}

- (void)clickBtn:(UIButton *)btn{
    self.model = self.data[btn.tag];
    DLog(@"-------%@",self.model.girded);
    
    if ([self.model.girded integerValue] == 40) {
        [CreaditUtilsHelper boxShowWithMessage:esString(self.model.ego)];
    }
    else if ([self.model.girded integerValue] == 50) {
        TipsAlertCancelView *tv = [[TipsAlertCancelView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withTitleStr:@"Account Cancellation" WithDescStr:@"Once an account is cancelled,it cannot be restared.To ensure the security of your account,please confirm that account-related services have been handled properly before submitting your application." withCancelStr:@"Cancel" withSureStr:@"Delete Account"];
        [[UIApplication sharedApplication].keyWindow addSubview:tv];
        
        tv.clickSureBlock = ^{
           
            [CreaditUtilsHelper boxShowLoadWithMessage:@""];
            NSMutableDictionary *dic = @{
                @"chelsea":@"chelseaClear",
            }.mutableCopy;
            [BaseDataEngine apiForPath:kUserLostUrl method:kGetMethod parameter:dic onCompleteSuccess:^(NSDictionary *responseDic) {
                DLog(@"======%@",responseDic);
                [CreaditUtilsHelper hideLoadMessageBox];
                if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
                    [CreaditUtilsHelper boxShowErrorWithMessage:esString(responseDic[@"platform"]) duration:2.5f];
                    return;
                }
                [CreditServerHelper logoutController];
            } onCompleteFailur:^(NSError *error) {
                [CreaditUtilsHelper hideLoadMessageBox];
            } withIsForm:NO];
            
        };
    }
    else if ([self.model.girded integerValue] == 60) {
        TipsAlertGoOutView *tv = [[TipsAlertGoOutView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withTitleStr:@"Go Out" WithDescStr:@"Are you sure you want to log out of your account?" withCancelStr:@"Cancel" withSureStr:@"Go Out"];
        [[UIApplication sharedApplication].keyWindow addSubview:tv];
        
        tv.clickSureBlock = ^{
            [CreaditUtilsHelper boxShowLoadWithMessage:@""];
            NSMutableDictionary *dic = @{
                @"acquaintance":@"acquaintanceLogOut",
                @"forgot":@"forgotLogOut",
            }.mutableCopy;
            [BaseDataEngine apiForPath:kUserLogoutUrl method:kGetMethod parameter:dic onCompleteSuccess:^(NSDictionary *responseDic) {
                DLog(@"======%@",responseDic);
                [CreaditUtilsHelper hideLoadMessageBox];
                if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
                    [CreaditUtilsHelper boxShowErrorWithMessage:esString(responseDic[@"platform"]) duration:2.5f];
                    return;
                }
                [CreditServerHelper logoutController];
            } onCompleteFailur:^(NSError *error) {
                [CreaditUtilsHelper hideLoadMessageBox];
            } withIsForm:NO];
        };
    }
    else{

        [[CreditCore globleCore] jumpToPage:esString(self.model.rode)];
        
    }
    
}
- (void)loadData{
    if (![[CurrentUser mine] hasLogged]) {
        return;
    }
        
    NSString *versonStr = [NSString stringWithFormat:@"Version:%@",kAppVersion];
    NSDictionary *dic4 = @{
        @"girded":@"40",
        @"ego":versonStr,
        @"serene":@"",
        @"rode":@"",
        @"btnImg":@"icon_btn4",
    };
    NSDictionary *dic5 = @{
        @"girded":@"50",
        @"ego":@"Account Cancellation",
        @"serene":@"",
        @"rode":@"",
        @"btnImg":@"icon_btn5",
    };
    NSDictionary *dic6 = @{
        @"girded":@"60",
        @"ego":@"Go Out",
        @"serene":@"",
        @"rode":@"",
        @"btnImg":@"icon_btn6",
    };
    
    NSMutableDictionary *muDic = @{@"lovable":@"lovablePersonCenter"}.mutableCopy;
    [BaseDataEngine apiForPath:kPersonCenterUrl method:kGetMethod parameter:muDic onCompleteSuccess:^(NSDictionary *responseDic) {
        DLog(@"======%@",responseDic);
        [CreaditUtilsHelper hideLoadMessageBoxFromView:self.view];
        [CreaditUtilsHelper hideLoadMessageBox];
        if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
            [CreaditUtilsHelper boxShowErrorWithMessage:esString(responseDic[@"platform"]) duration:2.5f];
            return;
        }
        
        
        NSDictionary *dic = responseDic[@"recollecting"];
        NSArray *pinAry = dic[@"pines"];
        
        NSMutableArray *muArr = [[NSMutableArray alloc] init];
        [muArr addObjectsFromArray:pinAry];
        [muArr addObject:dic4];
        [muArr addObject:dic5];
        [muArr addObject:dic6];
        
        self.data = [PersonCenterModel mj_objectArrayWithKeyValuesArray:muArr];
        
        [self initHeadView];
        
    } onCompleteFailur:^(NSError *error) {
        [CreaditUtilsHelper hideLoadMessageBoxFromView:self.view];
        [CreaditUtilsHelper hideLoadMessageBox];
    } withIsForm:NO];
    
    
    
    
    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 0.0001;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PersonCenterTableCell *cell = [tableView dequeueReusableCellWithIdentifier:kTabCell];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat offset_Y = scrollView.contentOffset.y;
    if (offset_Y < 0) {
        if (offset_Y < - kNavigationBarHeight) {
            self.isOffsetY = YES;
        }
    }else{
        if (self.isOffsetY) {
            self.isOffsetY = NO;
            [CreaditUtilsHelper boxShowLoadWithMessage:@"" onView:self.view withOffsetHeight:0];
            [self loadData];
        }
    }
}





@end
